<template>
    <view class="comm-list-container">
        <!-- 使用封装的页面头部组件 -->
        <page-header title="我发布的任务"></page-header>

        <view class="search-box">
            <uni-search-bar
                placeholder="请输入要搜索的作物内容"
                v-model="searchKeyword"
                @confirm="handleSearch"
                @input="handleSearch"
                :radius="100"
                cancelButton="none"></uni-search-bar>
        </view>

        <view class="list-filter-container">
            <view class="filter-picker" @click="openDatePopup">
                <text class="picker-label">{{ selectedTime || '时间' }}</text>
                <text class="picker-arrow">
                    <roc-icon-plus
                        type="fas"
                        name="angle-down"
                        :size="16"
                        color="#2E6140"></roc-icon-plus>
                </text>
            </view>
            <picker
                mode="selector"
                :range="statusOptions"
                range-key="name"
                @change="onStatusChange">
                <view class="filter-picker">
                    <text class="picker-label">{{ selectedStatus?.name || '状态' }}</text>
                    <text class="picker-arrow">
                        <roc-icon-plus
                            type="fas"
                            name="angle-down"
                            :size="16"
                            color="#2E6140"></roc-icon-plus>
                    </text>
                </view>
            </picker>
            <picker
                mode="selector"
                :range="areaOptions"
                range-key="name"
                :value="selectedAreaIndex"
                @change="onAreaChange">
                <view class="filter-picker">
                    <text class="picker-label">
                        {{ areaOptions[selectedAreaIndex]?.name || '地块' }}
                    </text>
                    <text class="picker-arrow">
                        <roc-icon-plus
                            type="fas"
                            name="angle-down"
                            :size="16"
                            color="#2E6140"></roc-icon-plus>
                    </text>
                </view>
            </picker>
        </view>

        <view class="comm-record-list">
            <record-item
                v-for="(item, index) in filteredTaskList"
                :key="index"
                :allCanEdit="true"
                :item="item"
                @clickItem="editTaskRecord(item)"
                @edit="editTaskRecord(item)"
                @delete="confirmDelete(item)">
                <template #header>
                    <view class="item-header">
                        <view style="display: flex; align-items: center">
                            <image
                                style="margin-right: 10rpx"
                                class="icon-wrapper"
                                :src="AGRICULTURAL_WORK_TYPES_CHART[item?.workTask]"
                                mode="aspectFill"></image>
                            <text class="date-title">{{ getWorkTypeLabel(item.workTask) }}</text>
                        </view>

                        <view class="task-status" :class="getStatusClass(item.status)">
                            {{ getStatusLabel(item.status) }}
                        </view>
                    </view>
                </template>
                <template #content>
                    <view class="item-content">
                        <div style="display: flex; justify-content: space-between">
                            <view class="info-row">
                                <text class="info-label">地块</text>
                                <text class="info-value">{{ item.fieldName }}</text>
                            </view>

                            <view class="info-row">
                                <text class="info-label">负责人</text>
                                <text class="info-value">{{ item.personInCharge }}</text>
                            </view>
                        </div>
                        <div style="display: flex; justify-content: space-between">
                            <view class="info-des">
                                {{ item.remarks }}
                            </view>
                        </div>
                        <div style="display: flex; justify-content: space-between">
                            <view class="info-row">
                                <text class="info-label">安排日历:</text>
                                <text class="info-value">
                                    {{ item.startDate }}-{{ item.endDate }}
                                </text>
                            </view>
                        </div>

                        <view class="item-images" v-if="item.images">
                            <image
                                v-for="(img, imgIndex) in formatImages(item.images).slice(0, 2)"
                                :key="imgIndex"
                                :src="img"
                                mode="aspectFit"></image>
                        </view>
                    </view>
                </template>
            </record-item>

            <!-- 加载更多提示 -->
            <view class="load-more-container" v-if="filteredTaskList.length > 0">
                <view v-if="loadingMore" class="loading-more">
                    <text class="loading-text">加载中...</text>
                </view>
                <view v-else-if="!hasMore" class="no-more">
                    <text class="no-more-text">没有更多数据了</text>
                </view>
            </view>
        </view>
        <!-- 无数据提示 -->
        <empty-data v-if="filteredTaskList.length === 0 && !loading"></empty-data>

        <view class="add-button" @click="navigateTo('/pages/my/taskManage/addTask')">
            <text class="add-icon">+</text>
        </view>

        <!-- 日期选择弹出层 -->
        <uni-popup ref="datePopup" type="center">
            <view class="popup-content">
                <view class="popup-title">选择日期范围</view>
                <view class="date-picker-container">
                    <view class="date-item">
                        <text>开始日期：</text>
                        <picker
                            mode="date"
                            :value="tempStartDate || dateRange.startDate"
                            @change="onStartDateChange">
                            <view class="picker-value">
                                {{ tempStartDate || dateRange.startDate || '请选择' }}
                            </view>
                        </picker>
                    </view>
                    <view class="date-item">
                        <text>结束日期：</text>
                        <picker
                            mode="date"
                            :value="tempEndDate || dateRange.endDate"
                            :start="tempStartDate || dateRange.startDate"
                            @change="onEndDateChange">
                            <view class="picker-value">
                                {{ tempEndDate || dateRange.endDate || '请选择' }}
                            </view>
                        </picker>
                    </view>
                </view>
                <view class="popup-buttons">
                    <button class="btn cancel" @click="cancelDatePicker">取消</button>
                    <button class="btn confirm" @click="confirmDatePicker">确定</button>
                </view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
import PageHeader from '@/components/PageHeader/index.vue'
import RecordItem from '@/components/RecordItem/index.vue'
import EmptyData from '@/components/EmptyData/index.vue'
import { getFarmingSchedulePage, deleteFarmingSchedule } from '@/utils/api/myTask.js'
import { formatDate, formatImages } from '@/utils/util.js'
import {
    AGRICULTURAL_WORK_TYPES,
    STATUS_DICT,
    getDictText,
    AGRICULTURAL_WORK_TYPES_CHART,
} from '@/utils/dict.js'
import { getAllParcelAndFields } from '@/utils/api/land.js'

export default {
    components: {
        PageHeader,
        RecordItem,
        EmptyData,
    },
    data() {
        return {
            title: '任务管理',
            searchKeyword: '',
            taskList: [],
            loading: false,
            loadingMore: false, // 加载更多状态
            hasMore: true, // 是否还有更多数据
            pageParams: {
                pageNo: 1,
                pageSize: 30,
            },
            // 新增的数据属性
            selectedTime: '',
            selectedStatus: null,
            selectedAreaIndex: 0,
            statusOptions: Object.entries(STATUS_DICT).map(([value, label]) => ({
                value,
                name: label,
            })),
            areaOptions: [{ name: '选择地块', id: '' }],
            showDatePopup: false,
            dateRange: {
                startDate: '',
                endDate: '',
            },
            tempStartDate: '', // 临时存储开始日期
            tempEndDate: '', // 临时存储结束日期
            AGRICULTURAL_WORK_TYPES_CHART,
        }
    },
    computed: {
        filteredTaskList() {
            return this.taskList
        },
    },
    onShow() {
        this.fetchTaskList()
        this.fetchAreaOptions() // 获取地块选项
    },
    onPullDownRefresh() {
        this.fetchTaskList()
    },
    // 触底加载更多
    onReachBottom() {
        this.loadMoreData()
    },
    methods: {
        // 获取地块选项
        async fetchAreaOptions() {
            try {
                const res = await getAllParcelAndFields()
                if (res.code === 0 && res.data && res.data.length > 0) {
                    this.areaOptions = [
                        { id: '', name: '全部地块' },
                        ...res.data.map((parcel) => ({
                            id: parcel.id,
                            name: parcel.parcelName,
                        })),
                    ]
                }
            } catch (error) {
                console.error('获取地块选项失败:', error)
                uni.showToast({
                    title: '获取地块选项失败',
                    icon: 'none',
                })
            }
        },

        // 日期选择相关方法
        openDatePopup() {
            this.tempStartDate = this.dateRange.startDate
            this.tempEndDate = this.dateRange.endDate
            this.$refs.datePopup.open()
        },

        onStartDateChange(e) {
            this.tempStartDate = e.detail.value
        },

        onEndDateChange(e) {
            this.tempEndDate = e.detail.value
        },

        cancelDatePicker() {
            this.tempStartDate = ''
            this.tempEndDate = ''
            this.$refs.datePopup.close()
        },

        confirmDatePicker() {
            if (this.tempStartDate && this.tempEndDate) {
                this.dateRange.startDate = this.tempStartDate
                this.dateRange.endDate = this.tempEndDate
                this.selectedTime = `${this.tempStartDate} ~ ${this.tempEndDate}`

                // 更新查询参数
                this.pageParams.startDate = this.tempStartDate
                this.pageParams.endDate = this.tempEndDate

                // 重新加载数据
                this.fetchTaskList()
            }
            this.$refs.datePopup.close()
        },

        onStatusChange(e) {
            const index = e.detail.value
            this.selectedStatus = this.statusOptions[index]
            this.pageParams.status = this.selectedStatus.value
            this.fetchTaskList()
        },

        onAreaChange(e) {
            this.selectedAreaIndex = e.detail.value
            const selectedArea = this.areaOptions[this.selectedAreaIndex]
            this.pageParams.plotId = selectedArea.id
            this.fetchTaskList()
        },

        handleDateConfirm(dates) {
            if (dates && dates.length === 2) {
                this.dateRange.startDate = dates[0]
                this.dateRange.endDate = dates[1]
                this.selectedTime = `${dates[0]} ~ ${dates[1]}`
                this.pageParams.startDate = dates[0]
                this.pageParams.endDate = dates[1]
                this.fetchTaskList()
            }
            this.showDatePopup = false
        },

        getWorkTypeLabel(value) {
            if (!value) return '未指定'
            return getDictText(AGRICULTURAL_WORK_TYPES, value, value)
        },

        getStatusLabel(status) {
            if (!status) return '未开始'
            return getDictText(STATUS_DICT, status, status)
        },

        getStatusClass(status) {
            const statusMap = {
                0: 'status-pending',
                1: 'status-in-progress',
                2: 'status-completed',
            }
            return statusMap[status] || 'status-pending'
        },

        handleFilterChange(tabValue, filterData) {
            this.activeTab = tabValue

            // 重置页码
            this.pageParams.pageNo = 1
            this.hasMore = true // 重置加载更多状态

            // 清除之前的日期和地块筛选条件
            delete this.pageParams.startDate
            delete this.pageParams.endDate
            delete this.pageParams.plotId

            // 添加新的筛选条件
            if (filterData) {
                if (filterData.startDate && filterData.endDate) {
                    this.pageParams.startDate = filterData.startDate
                    this.pageParams.endDate = filterData.endDate
                }

                if (filterData.areaId) {
                    this.pageParams.plotId = filterData.areaId
                }
            }

            // 重新请求接口
            this.fetchTaskList()
        },

        handleSearch(e) {
            // 重置页码
            this.pageParams.pageNo = 1
            this.hasMore = true // 重置加载更多状态

            // 更新关键词搜索参数
            if (this.searchKeyword) {
                this.pageParams.keyword = e || this.searchKeyword
            } else {
                delete this.pageParams.keyword
            }

            // 重新请求接口
            this.fetchTaskList()
        },

        async fetchTaskList(isLoadMore = false) {
            try {
                if (isLoadMore) {
                    this.loadingMore = true
                } else {
                    this.loading = true
                    uni.showLoading({ title: '加载中...' })
                }

                const res = await getFarmingSchedulePage(this.pageParams)

                if (res.code === 0 && res.data) {
                    const newList = res.data.list || []

                    if (isLoadMore) {
                        // 加载更多时追加数据
                        this.taskList = [...this.taskList, ...newList]
                    } else {
                        // 首次加载或刷新时替换数据
                        this.taskList = newList
                    }

                    // 判断是否还有更多数据
                    this.hasMore = newList.length >= this.pageParams.pageSize
                }
            } catch (error) {
                console.error('获取任务列表失败:', error)
                if (!isLoadMore) {
                    uni.showToast({
                        title: '获取数据失败',
                        icon: 'none',
                    })
                }
            } finally {
                this.loading = false
                this.loadingMore = false
                uni.hideLoading()
                uni.stopPullDownRefresh()
            }
        },

        navigateTo(url) {
            uni.navigateTo({ url })
        },

        formatDate(dateString) {
            return formatDate(dateString)
        },

        formatImages(imagesStr) {
            return formatImages(imagesStr)
        },

        viewDetail(item) {
            uni.navigateTo({
                url: `/pages/my/taskManage/addTask?id=${item.id}`,
            })
        },

        editTaskRecord(item) {
            console.log('编辑任务', item)
            // 检查任务状态
            if (item.status === '1' || item.status === '2') {
                uni.showToast({
                    title: '已完成或部分完成的任务不能编辑',
                    icon: 'none',
                })
                return
            }

            uni.navigateTo({
                url: `/pages/my/taskManage/addTask?id=${item.id}`,
            })
        },

        confirmDelete(item) {
            // 检查任务状态
            if (item.status === '1' || item.status === '2') {
                uni.showToast({
                    title: '已完成或部分完成的任务不能删除',
                    icon: 'none',
                })
                return
            }

            uni.showModal({
                title: '确认删除',
                content: `确定要删除这条任务记录吗？`,
                success: (res) => {
                    if (res.confirm) {
                        this.deleteTask(item.id)
                    }
                },
            })
        },

        async deleteTask(id) {
            try {
                uni.showLoading({ title: '删除中...' })

                const res = await deleteFarmingSchedule(id)

                if (res.code === 0) {
                    // 删除成功，更新列表
                    const index = this.taskList.findIndex((item) => item.id === id)
                    if (index !== -1) {
                        this.taskList.splice(index, 1)
                    }

                    uni.showToast({
                        title: '删除成功',
                        icon: 'success',
                    })
                } else {
                    uni.showToast({
                        title: res.msg || '删除失败',
                        icon: 'none',
                    })
                }
            } catch (error) {
                console.error('删除任务失败:', error)
                uni.showToast({
                    title: '删除失败',
                    icon: 'none',
                })
            } finally {
                uni.hideLoading()
            }
        },

        // 加载更多数据
        async loadMoreData() {
            if (this.loadingMore || !this.hasMore) {
                return
            }

            this.pageParams.pageNo += 1
            await this.fetchTaskList(true)
        },
    },
}
</script>

<style lang="scss">
.list-filter-container {
    display: flex;
    justify-content: space-between;
    padding: 10px;

    .filter-picker {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin: 0 5px;
        padding: 10px 12px;
        background-color: #fff;
        border: 1px solid #e5e5e5;
        border-radius: 8px;
        font-size: 15px;
        color: #333;
        position: relative;
        min-width: 0;
        box-sizing: border-box;

        .picker-label {
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            text-align: left;
        }

        .picker-arrow {
            margin-left: 8px;
            font-size: 13px;
            color: #999;
        }
    }
}

.popup-content {
    width: 600rpx;
    background-color: #ffffff;
    border-radius: 10px;
    padding: 20px;

    .popup-title {
        font-size: 18px;
        font-weight: bold;
        text-align: center;
        margin-bottom: 20px;
    }

    .date-picker-container {
        margin-bottom: 20px;

        .date-item {
            display: flex;
            align-items: center;
            margin-bottom: 10px;

            .picker-value {
                flex: 1;
                border: 1px solid #ccc;
                border-radius: 5px;
                padding: 5px;
                text-align: center;
                width: 300rpx;
            }
        }
    }

    .popup-buttons {
        display: flex;
        justify-content: space-between;

        .btn {
            flex: 1;
            margin: 0 5px;
            padding: 10px;
            border-radius: 5px;
            text-align: center;
            font-size: 16px;

            &.cancel {
                background-color: #f5f5f5;
                color: #333;
            }

            &.confirm {
                background-color: #2e6140;
                color: #fff;
            }
        }
    }
}

.info-des {
    margin: 0 0 10rpx 0;
    font-family: OPPOSans, OPPOSans;
    font-weight: 500;
    font-size: 24rpx;
    color: #0d72ff;

    padding: 4rpx 10rpx;
    background: rgba(238, 245, 253, 0.8);
}
</style>
